package com.borya.action.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.borya.action.BaseAction;
import com.borya.framework.annotation.Action;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.JsonResult;
import com.borya.framework.annotation.UrlMapping;
import com.borya.framework.core.ServerRequest;
import com.borya.framework.core.ServerResponse;
import com.borya.model.db.Merchant;
import com.borya.model.db.WhiteConfig;
import com.borya.model.entity.PageArgs;
import com.borya.model.entity.PageData;
import com.borya.model.entity.WhiteProd;
import com.borya.service.web.WhiteListService;
import com.borya.statuscode.StatusCode;
import com.borya.util.DateUtils;
import com.borya.util.StringUtil;

@UrlMapping("/w/whiteList/")
@Action
public class WhiteListAction extends BaseAction{
	private Logger log = Logger.getLogger(getClass());
	
	@Autowired("whiteListServiceImpl")
	private WhiteListService whiteListService;

	public WhiteListService getWhiteListService() {
		return whiteListService;
	}


	public void setWhiteListService(WhiteListService whiteListService) {
		this.whiteListService = whiteListService;
	}

	@UrlMapping("addWhiteProd") 
	@JsonResult
	public String addWhiteProd(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[logout:" + json + "]");
		String locationDes = json.getString("locationDes");//详细地名
		if(StringUtil.isNULL(locationDes) || !json.containsKey("remark")){
			log.warn("param cityCode/pointStr error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		WhiteProd whiteProd = new WhiteProd();
		whiteProd.setLocationDes(locationDes);
		long nowTime = System.currentTimeMillis();
		whiteProd.setCreateTime(nowTime);
		final String tDateStr = DateUtils.format(nowTime, "yyMMddHHmmss");
		whiteProd.setProdId("P"+tDateStr+StringUtil.randomNumberString(4));
		whiteProd.setRemark(json.getString("remark"));
		try {
			boolean res = getWhiteListService().addWhiteProd(whiteProd);
			log.info("OUT[" + res + "]");
			if(! res){
				log.warn("addWhiteProd return false");
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			return StatusCode.SUCCESS.toJSON();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
	}
	
	@UrlMapping("findWhiteProdList") 
	@JsonResult
	public String findWhiteProdList(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[logout:" + json + "]");
		try {
			List<WhiteProd> list = getWhiteListService().findWhiteProdList();
			log.info("findWhiteProdList,OUT[" + list + "]");
			if(list==null){
				log.warn("findWhiteProdList return null");
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			return StatusCode.SUCCESS.toDiyJson(true, "data", JSON.toJSON(list).toString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
	}
	
	@UrlMapping("deleteWhiteProd") 
	@JsonResult
	public String deleteWhiteProd(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[logout:" + json + "]");
		String prodId = json.getString("prodId");//白名单编号
		if(StringUtil.isNULL(prodId)){
			log.warn("param prodId error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		try {
			boolean usedWhiteProdId = getWhiteListService().isUsedWhiteProdId(prodId);
			if(usedWhiteProdId){
				StringBuilder notice=new StringBuilder(64);
				notice.append("区域白名单[").append(prodId).append("]").append("已关联商户");
				return StatusCode.SYSTEM_EXCEPTION.toJSON(notice.toString());
			}
			boolean flag = getWhiteListService().deleteWhiteProd(prodId);
			log.info("deleteWhiteProd,OUT[" + flag + "]");
			if(flag==false){
				log.warn("deleteWhiteProd return null");
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			return StatusCode.SUCCESS.toJSON();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
	}
	
	@UrlMapping("merchantConfigList") 
	@JsonResult
	public String MerchantConfigList(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[" + json + "]");
		if(!json.containsKey("dealerId")){
			log.warn("param dealerId error");
			return StatusCode.PARAM_ERROR.toJSON("商户id参数错误");
		}
		if(!json.containsKey("startTime")||!json.containsKey("endTime")){
			log.warn("param dealerId error");
			return StatusCode.PARAM_ERROR.toJSON("时间参数错误");
		}
		if(!json.containsKey("pageSize")||!json.containsKey("pageNum")){
			log.warn("param dealerId error");
			return StatusCode.PARAM_ERROR.toJSON("分页参数错误");
		}
		//查询条件
		String dealerId = json.getString("dealerId");//商户id
		String startTime = json.getString("startTime");//开始时间
		String endTime = json.getString("endTime");//开始时间
		Integer pageSize = json.getInteger("pageSize");
		Integer pageNum = json.getInteger("pageNum");
		try {
			long parseStartTime = DateUtils.parseDate(startTime,"yyyy-MM-dd HH:mm:ss");
			long parseEndTime = DateUtils.parseDate(endTime,"yyyy-MM-dd HH:mm:ss");
			PageArgs pageArgs =new PageArgs(parseStartTime,parseEndTime,pageSize,pageNum);
			PageData<Merchant> pageData=getWhiteListService().getMerchantConfigByPage(dealerId,pageArgs);
			if(pageData==null)
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			HashMap<String, Object> hashMap = new HashMap<>();
			hashMap.put("total", pageData.getTotal());
			hashMap.put("list", pageData.getDatas());
			String jsonString = JSONObject.toJSONString(hashMap,SerializerFeature.WriteMapNullValue);
			log.info("OUT[" + jsonString + "]");
			return StatusCode.SUCCESS.toDiyJson(true,"data", jsonString);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
	}
	@UrlMapping("structureScopes") 
	@JsonResult
	public String StructureScopes(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[" + json + "]");
		//查询条件
		String dealerId = json.getString("dealerId");//商户id
		if(StringUtil.isNULL(dealerId)){
			log.warn("param dealerId error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		try {
			List<WhiteConfig> merchants=getWhiteListService().StructureScopes(dealerId);
			HashMap<String, List<WhiteConfig>> hashMap = new HashMap<String,List<WhiteConfig>>();
			if(merchants==null){
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			for(WhiteConfig wc : merchants){
				String type = wc.getType()+"";
				if(!hashMap.containsKey(type)){
					ArrayList<WhiteConfig> list = new ArrayList<WhiteConfig>();
					hashMap.put(type, list);
				}
				List<WhiteConfig> list = hashMap.get(type);
				list.add(wc);
			}
			List<WhiteProd> whiteProdList = getWhiteListService().findWhiteProdList();
			if(whiteProdList==null){
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			JSONObject whitesObj = new JSONObject();
			for(WhiteProd wp:whiteProdList)
				whitesObj.put(wp.getProdId(), wp.getLocationDes());
			
			JSONObject data = new JSONObject();
			data.put("whiteList", whitesObj);
			data.put("whiteConfig", JSON.toJSON(hashMap));
			log.info("OUT[" + data + "]");
			return StatusCode.SUCCESS.toDiyJson("data", data);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
	}
	@UrlMapping("updateScopeConfig") 
	@JsonResult
	public String updateScopeConfig(ServerRequest request,ServerResponse response) {
		final JSONObject json = getJson(request);
		log.info("INFO[" + json + "]");
		//查询条件
		String configId = json.getString("configId");//配置项编码
		String isLocal = json.getString("isLocal");//是否开启本机校验
		if(StringUtil.isNULL(configId)){
			log.warn("param configId error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		if(StringUtil.isNULL(isLocal) || !"0,1".contains(isLocal)){
			log.warn("param isLocal error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		if(!json.containsKey("whiteIds")){
			log.warn("param whiteIds error");
			return StatusCode.PARAM_ERROR.toJSON("参数错误");
		}
		String whiteIds = json.getString("whiteIds");//配置的白名单编码，多有用逗号分隔
		try {
			boolean flag=getWhiteListService().updateScopeConfig(configId,isLocal,whiteIds);
			log.info("OUT[" + flag + "]");
			return StatusCode.SUCCESS.toJSON();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.toJSON(e.getMessage());
		}
	}
	
}
